//
//  HDMainViewController.m
//  HDecoration
//
//  Created by koki on 15-5-6.
//  Copyright (c) 2015年 HDecoration. All rights reserved.
//
typedef NS_ENUM(NSInteger, HDMainVCBottomBtn) {
    HDMainVCBottomBtnPractice = 100,
    HDMainVCBottomBtnLearn,
    HDMainVCBottomBtnPersonal
};

#import "HDMainViewController.h"
#import "HDPracticeViewController.h"
#import "HDPersonalViewController.h"
#import "HDMessageViewController.h"
#import "HDMapViewController.h"
#import "APService.h"
#import "EntryView.h"

@interface HDMainViewController ()

@property HDBaseViewController* curVctr;
@property(nonatomic,strong)GXButton *messageBtn;
@property(nonatomic,strong)UIButton *practiceBtn;
@property(nonatomic,strong)UIButton *learnBtn;
@property(nonatomic,strong)UIButton *personalBtn;
@property(nonatomic,strong)HDOrderView *orderView;
@property(nonatomic,strong)HDCustomerInfo *currentOrderInfo;
@property(nonatomic,assign)int interval;    //用于测试的计时器时间
@property(nonatomic,strong)AsyncSocket * asyncSocket;
@property(nonatomic,assign)BOOL bReconnet;
@property(nonatomic,strong)EntryView* entryView;
@property (nonatomic)  DOImageView* tipView;
@end

@implementation HDMainViewController
@synthesize asyncSocket;


- (void)initUI
{
    self.view.backgroundColor = kContentViewColor;
    [self.view addSubview:self.practiceBtn];
    [self.view addSubview:self.learnBtn];
    [self.view addSubview:self.personalBtn];
    [self.view addSubview:self.orderView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showMsgTip) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    [self.view addSubview:self.tipView];
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [window addSubview:self.entryView];
    
}

-(DOImageView*)tipView
{
    if (_tipView==nil)
    {
        
        float x=(APPFRAME.size.width-216)/2.0;
        float y=(SCREENFRAME.size.height-240)/2.0+65;
        CGRect rect=CGRectMake(x,y, 216, 118);
        _tipView=[[DOImageView alloc] initWithFrame:rect];
        _tipView.imgURLStr=@"bg0";
    }
    return _tipView;
}

-(EntryView*)entryView
{
    if (_entryView==nil)
    {
       _entryView=[[EntryView alloc] initWithFrame:SCREENFRAME];
    }
    return _entryView;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)showMsgTip
{
    self.messageBtn.numberCount = 1;
}

- (void)initNavigationBar
{
    UIImageView *titleView = [[UIImageView alloc] initWithFrame:CGRectMake((APPFRAME.size.width-80)/2.0, 15, 80, 35)];
    titleView.image = [UIImage imageNamed:@"导航栏标题"];
    titleView.contentMode = UIViewContentModeScaleAspectFit;
    titleView.layer.masksToBounds = YES;
    self.navigationItem.titleView = titleView;
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 60, 40);
    [leftBtn setTitle:@"我的位置" forState:UIControlStateNormal];
    [leftBtn setTitleColor:kDarkGrayColor forState:UIControlStateNormal];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [leftBtn addTarget:self action:@selector(leftBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.messageBtn];
}

- (void)leftBtnAction:(UIButton *)sender
{
    HDMapViewController *mapVC = [[HDMapViewController alloc] init];
    mapVC.navigationItem.title = @"我的位置";
    [self.navigationController pushViewController:mapVC animated:YES];
}

- (void)bottomBtnAction:(UIButton *)sender
{
    switch (sender.tag) {
        case HDMainVCBottomBtnPractice: //练车
        {
            HDPracticeViewController *practiceVC = [[HDPracticeViewController alloc] init];
            practiceVC.navigationItem.title = @"练车";
            practiceVC.orderType = HDOrderTypePractice;
            [self.navigationController pushViewController:practiceVC animated:YES];
            break;
        }
        case HDMainVCBottomBtnLearn:    //学车
        {
            HDPracticeViewController *learnVC = [[HDPracticeViewController alloc] init];
            learnVC.navigationItem.title = @"学车";
            learnVC.orderType = HDOrderTypeLearn;
            [self.navigationController pushViewController:learnVC animated:YES];
            break;
        }
        case HDMainVCBottomBtnPersonal: //个人中心
        {
            HDPersonalViewController *personal = [[HDPersonalViewController alloc] init];
            personal.navigationItem.title = @"个人中心";
            [self.navigationController pushViewController:personal animated:YES];
            break;
        }
        default:
            break;
    }
}

- (void)orderViewAcceptOrder
{
    
    NSDictionary* params=@{
                           @"coach_id":netEngine.coachInfo.m_id,
                           @"id":self.currentOrderInfo.order_id,
                           @"coach_name":netEngine.coachInfo.real_name,
                           @"coach_no":netEngine.coachInfo.coach_no,
                           };
    [netEngine RequestAcceptOrderWithTarget:self.VctrID hudView:self.contentView Data:params];
    
}

-(void)updateViewController:(NSNotification *)note
{
    NSDictionary* dic=note.userInfo;
    if ([dic objectForKey:Receiver]==self.VctrID)
    {
        if (dic[@"AcceptOrder"]!=nil)
        {
            [self.orderView dismiss];
            self.tipView.hidden=NO;
        }
    }
}


#pragma mark  socket

-(void)createSocketRequest
{
    asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
    [asyncSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
    
    NSError *err = nil;
    if(![asyncSocket connectToHost:netEngine.coachInfo.cservice onPort:[netEngine.coachInfo.pport intValue] error:&err])
    {
        NSLog(@"Error: %@", err);
    }
}


- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSString* strContent=[NSString stringWithFormat:@"ID:%@",netEngine.coachInfo.m_id];
    NSData* aData= [strContent dataUsingEncoding: NSUTF8StringEncoding];
    
    
    Byte *testByte = (Byte *)[aData bytes];
    aData=[NSData dataWithBytes:testByte length:[aData length]];
    [sock writeData:aData withTimeout:-1 tag:1];
    
    [sock readDataWithTimeout:-1 tag:0];
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    if (self.bReconnet)
    {
        [self createSocketRequest];
    }
}

-(void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *result=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSData *responseData = [result dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary* json =[NSJSONSerialization
                         JSONObjectWithData:responseData
                         options:kNilOptions
                         error:nil];
    
    if (json!=nil && [json isKindOfClass:[NSArray class]])
    {
        NSDictionary* item=((NSArray*)json)[0];
        if (item[@"end"]!=nil)
        {
            [self.orderView dismiss];
            self.tipView.hidden=NO;
        }
        else
        {
            [self parseOrder:item];
        }
    }
    
    NSLog(@"%@",json);
    
    
    
    [sock readDataWithTimeout:-1 tag:0];
}


-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"didWriteDataSuccess");
}


- (void)viewWillDisappear:(BOOL)animated
{
    self.bReconnet=NO;
    NSData* aData= [@"quit" dataUsingEncoding: NSUTF8StringEncoding];
    [asyncSocket writeData:aData withTimeout:-1 tag:1];
    
    [asyncSocket disconnect];
    asyncSocket=nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.bReconnet=YES;
    [self createSocketRequest];
    
    ////1教练 2陪练,
    if ([netEngine.coachInfo.user_type intValue]==1)
    {
        self.practiceBtn.enabled=NO;
        self.learnBtn.enabled=YES;
    }
    else if ([netEngine.coachInfo.user_type intValue]==2)
    {
        self.practiceBtn.enabled=YES;
        self.learnBtn.enabled=NO;
    }
    
    if ([netEngine.coachInfo.messageNum intValue])
    {
        [self showMsgTip];
    }
}

-(void)parseOrder:(NSDictionary*)data
{
    HDCustomerInfo *customerInfo = [[HDCustomerInfo alloc] init];
    //添加解析
    int category=[[HDUtil check:data[@"category"]] intValue];
    NSArray* array=@[@"无",@"科目一",@"科目二",@"科目三",@"科目四",@"科目五",@"科目六"];
    category=MIN(category, (int)array.count-1);
    customerInfo.subject = array[category];
    customerInfo.photoUrl = [HDUtil check:data[@"user_picture"]];
    customerInfo.stationTime = [HDUtil check:data[@"total_hours"]];
    customerInfo.name=[HDUtil check:data[@"student_name"]];
    customerInfo.type=[HDUtil check:data[@"car_type"]];
    customerInfo.remark = [HDUtil check:data[@"remark"]];
    customerInfo.price = [HDUtil check:data[@"order_money"]];
    customerInfo.practicePosition = [HDUtil check:data[@"training_field"]];
    customerInfo.needCompany = [[HDUtil check:data[@"ispick"]] boolValue];
    customerInfo.order_id=[HDUtil check:data[@"id"]];
    customerInfo.learnTime = [HDUtil check:data[@"order_hours"]];
    
    NSArray* array01=@[@"无",@"待支付",@"退单申请中",@"已支付",@"已抢单",@"已拒绝",@"进行中",@"已完成",@"已退单完成",@"退单已拒绝"];
    int state=[[HDUtil check:data[@"state"]] intValue];
    state=MIN(state, (int)array01.count-1);
    customerInfo.orderStatus = array01[state];
    
    int orderType=[[HDUtil check:data[@"order_type"]] intValue];
    customerInfo.orderType=(orderType==1)?HDOrderTypeLearn:HDOrderTypePractice;
    customerInfo.phoneNumber=[HDUtil check:data[@"mobile_no"]];
    customerInfo.startTime=[HDUtil checkNumber:data[@"start_time"]];
    customerInfo.endTime=[HDUtil checkNumber:data[@"end_time"]];
    customerInfo.price = [HDUtil check:data[@"order_money"]];
    
    NSString* xy=[HDUtil check:data[@"xy"]];
    xy=[xy stringByReplacingOccurrencesOfString:@"(" withString:@""];
    xy=[xy stringByReplacingOccurrencesOfString:@")" withString:@""];
    NSArray* array02=[xy componentsSeparatedByString:@","];
    if(array02.count>1)
    {
        customerInfo.latitude=[array02[0] floatValue];
        customerInfo.longitude=[array02[1] floatValue];
    }
    else
    {
       customerInfo.xy=@"";
    }
    
    customerInfo.location=[HDUtil check:data[@"address"]];
    customerInfo.content=[HDUtil check:data[@"content"]];
    self.currentOrderInfo = customerInfo;
    
    [self.orderView showWithData:self.currentOrderInfo];
    [netEngine startBroadcast:self.currentOrderInfo.content];
    self.tipView.hidden=YES;
}


//##############################################

-(void)testDataFunc
{
    
}

- (void)showOrder:(NSTimer *)timer
{
    self.interval++;
    self.currentOrderInfo = timer.userInfo[self.interval%2];
    [self.orderView showWithData:self.currentOrderInfo];
}

- (void)msgBtnAction:(UIButton *)sender
{
    self.messageBtn.numberCount = 0;
    netEngine.coachInfo.messageNum=@"0";
    HDMessageViewController *messageVC = [[HDMessageViewController alloc] init];
    messageVC.navigationItem.title = @"消息中心";
    [self.navigationController pushViewController:messageVC animated:YES];
}


#pragma mark - getters
- (GXButton *)messageBtn
{
    if (!_messageBtn) {
        _messageBtn = [GXButton buttonWithType:UIButtonTypeCustom];
        _messageBtn.frame = CGRectMake(0, 0, 40, 40);
        _messageBtn.imageViewFrame = CGRectMake(9, 12, 22, 15);
        _messageBtn.relayout = YES;
        _messageBtn.showTip = YES;
        [_messageBtn setImage:[UIImage imageNamed:@"消息.png"] forState:UIControlStateNormal];
        [_messageBtn addTarget:self action:@selector(msgBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _messageBtn;
}

- (UIButton *)practiceBtn
{
    if (!_practiceBtn) {
        _practiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _practiceBtn.frame = CGRectMake((APPFRAME.size.width-260)/4.0, SCREENFRAME.size.height-55, 80, 45);
        [_practiceBtn setBackgroundImage:[UIImage imageNamed:@"练车"] forState:UIControlStateNormal];
        [_practiceBtn setBackgroundImage:[UIImage imageNamed:@"disableBackgroundImage"] forState:UIControlStateDisabled];
        _practiceBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_practiceBtn setTitle:@"练车" forState:UIControlStateNormal];
        [_practiceBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _practiceBtn.tag = HDMainVCBottomBtnPractice;
        [_practiceBtn addTarget:self action:@selector(bottomBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _practiceBtn;
}

- (UIButton *)learnBtn
{
    if (!_learnBtn) {
        _learnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _learnBtn.frame = CGRectMake(self.practiceBtn.right+(APPFRAME.size.width-260)/4.0, SCREENFRAME.size.height-55, 80, 45);
        [_learnBtn setBackgroundImage:[UIImage imageNamed:@"学车"] forState:UIControlStateNormal];
        [_learnBtn setBackgroundImage:[UIImage imageNamed:@"disableBackgroundImage"] forState:UIControlStateDisabled];
        _learnBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_learnBtn setTitle:@"学车" forState:UIControlStateNormal];
        [_learnBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _learnBtn.tag = HDMainVCBottomBtnLearn;
        [_learnBtn addTarget:self action:@selector(bottomBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _learnBtn;
}

- (UIButton *)personalBtn
{
    if (!_personalBtn) {
        _personalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _personalBtn.frame = CGRectMake(self.learnBtn.right+(APPFRAME.size.width-260)/4.0, SCREENFRAME.size.height-55, 100, 45);
        [_personalBtn setBackgroundImage:[UIImage imageNamed:@"个人中心"] forState:UIControlStateNormal];
        _personalBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_personalBtn setTitle:@"个人中心" forState:UIControlStateNormal];
        [_personalBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _personalBtn.tag = HDMainVCBottomBtnPersonal;
        [_personalBtn addTarget:self action:@selector(bottomBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _personalBtn;
}

- (HDOrderView *)orderView
{
    if (!_orderView) {
        _orderView = [[HDOrderView alloc] initWithFrame:CGRectMake(0, 74, APPFRAME.size.width, APPFRAME.size.height-119)];
        _orderView.delegate = (id)self;
    }
    return _orderView;
}

@end
